/**
 * This file is a part of qloudgen-sec. 
 * You can redistribute qloudgen-sec and/or modify it under the terms of the Lesser GNU General Public License version 3. 
 * qloudgen-sec is distributed WITHOUT ANY WARRANTY. 
 *
 * See the Lesser GNU General Public License for more details at http://www.gnu.org/licenses/. 
 **/
package org.qloudgen.sec.shiro.session;

import java.io.Serializable;

import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionIdGenerator;
import org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>Title: Session Listener Implementation</p>
 * <p>Description: Wrappered session listener implementation for osgi service.</p>
 * <p>Copyright: qloudgen/sec 2014</p>
 * @author <a href="mailto:hyq.dd.sun@gmail.com">glue.3M</a>
 */
public class TicketSessionIdGenerator implements SessionIdGenerator {
	/**
	 * Log output.
	 */
	private final static Logger logger = LoggerFactory.getLogger( TicketSessionIdGenerator.class );
	/**
	 *
	 */
	public final static String SESSION_ID = TicketSessionIdGenerator.class.getName() + ".SESSION_ID";
	/**
	 *
	 */
	private SessionIdGenerator internalSessionIdGenerator = null;
	
	/**
	 *
	 */
	public TicketSessionIdGenerator() {
		this.internalSessionIdGenerator = new JavaUuidSessionIdGenerator();
	}
	
	/**
	 *
	 */
	public Serializable generateId(Session session) {
		/**
		 * First we do need check current thread context session id.
		 */
		Serializable sessionId = ( Serializable )ThreadContext.get( SESSION_ID );
		if ( sessionId != null ) {
			logger.debug( "Current thread context session id not null..." );
			return sessionId;
		}
		/**
		 * Second
		 */
		logger.debug( "Current thread context session is null and will use default generator..." );
		return internalSessionIdGenerator.generateId( session );
	}
}